package com.education.basic.ao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.yunshangwoniu.core.baseService.BaseService;
import com.yunshangwoniu.core.baseService.PageService;
import com.yunshangwoniu.core.page.Page;
import com.yunshangwoniu.core.utils.Logger;
import com.yunshangwoniu.core.utils.RequestUtils;

public abstract class BaseAo<T>
{
	@Resource
	private BaseService<T> baseService;
	@Resource 
	private PageService<T> pageService;
	
	public Page<T> page(int currentPage, int pageSize, Map<String, Object> params,HttpServletRequest request,Class<?> c)
	{
		Logger.debug(this.getClass(), String.format("excute page from %s when currentPage:%s and pageSize:%s",c.getSimpleName(),currentPage,pageSize ));
		Page<T> page = new Page<T>(currentPage, pageSize, RequestUtils.getPageUrl(request));
		page.setParams(params);
		page = baseService.queryObject(page, c);
		pageService.htmlBuilder(page, "default");
		Logger.debug(this.getClass(), "================"+page.getPageCententHTML());
		return page;
	}

	public T insert(T t,Class<?> c)
	{
		return baseService.saveObject(t);
	}

	public void remove(long id,Class<?> c)
	{
		Logger.debug(this.getClass(), String.format("excute delete from %s where id:%s", c.getSimpleName(),id));
		baseService.deleteObjectById(c, id);
	}

	public void update(T d)
	{
		Logger.debug(this.getClass(), String.format("excete update from %s", d.getClass()));
		baseService.updateObject(d);
	}

	public T findById(long id,Class<?> c)
	{
		Logger.debug(this.getClass(), String.format("excete findById from %s when id:%s", c.getSimpleName(),id));
		return baseService.getObjectById(c, id);
	}

	public Page<T> findByName(String name, HttpServletRequest request,Class<?> c)
	{
		Logger.debug(this.getClass(), String.format("execute searching from %s name is :%s", c.getName(),name));
		Page<T> page = new Page<T>(1,10,RequestUtils.getPageUrl(request));
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("name", name.trim());
		page.setParams(params);
		baseService.queryObject(page, c);
		pageService.htmlBuilder(page, "default");
		
		return page ;
	}

	public void batchDelete(List<Long> ids,Class<?> c)
	{
		Logger.debug(this.getClass(), String.format("excete batchDelete List<Long> ids size is ", ids.size()));
		baseService.batchDeleteObject(ids, c);
	}
}
